package com.why.biyesheji.controller.mall;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.why.biyesheji.pojo.Product;
import com.why.biyesheji.service.IFileService;
import com.why.biyesheji.service.IProductService;
import com.why.biyesheji.service.impl.FileServiceImpl;
import com.why.biyesheji.util.FTPUtil;
import com.why.biyesheji.util.PropertiesUtil;
import com.why.biyesheji.util.Result;
import com.why.biyesheji.util.ResultGenerator;
import com.why.biyesheji.vo.IndexNewProductVO;
import com.why.biyesheji.vo.WangEditorVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * Created by 华耀 王 on 2020/10/15
 **/
@Controller
public class IndexController {

    @Value("${file.address}")
    private String filePath;

    @Autowired
    private IProductService iProductService;

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    private IFileService iFileService;

    @GetMapping({"/upload","/upload.html"})
    public String uploadPage(){
        return "mall/FileUploadTest";
    }

    @PostMapping("/uploadimg")
    @ResponseBody
    public Result upload(@RequestParam(value = "file",required = false)MultipartFile file) throws FileNotFoundException {
        //填充业务
        System.out.println(file.getOriginalFilename());
//        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        File path = new File(filePath);
        System.out.println("path"+path);// pathE:\IntelliJ%20IDEA\biyesheji\target\classes
        //文件上传的路径放入编译target目录下面 2、服务器的路径
        File upload = new File(path.getAbsolutePath(), "/upload");
        System.out.println("upload"+upload); // upload E:\IntelliJ%20IDEA\biyesheji\target\classes\static\ upload


        String fileName = file.getOriginalFilename();
        //扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;
        logger.info("开始上传文件，上传文件名为：{"+fileName+"}，上传文件路径为：{"+upload+"}，新的上传文件名为：{"+uploadFileName+"}");
        if (!upload.exists()){
            upload.setWritable(true); // writable：如果为true，允许写访问权限;如果为false，写访问权限是不允许的。
            upload.mkdirs();
        }
        File targetFile = new File(upload,uploadFileName);

        try {
            file.transferTo(targetFile);//使用transferTo（dest）方法将上传文件写到服务器上指定的文件。
            //文件上传成功了

            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            //已上传到FTP服务器上

            targetFile.delete();
            // 删除上传到服务器的图片文件，FTP服务器上的文件不影响
        } catch (IOException e) {
            logger.error("上传文件异常",e);
        }

        String targetFileName =  targetFile.getName();


        String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        if (targetFileName == null){
            return ResultGenerator.getFailResult("上传错误");
        }
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        return ResultGenerator.getSuccessResult(fileMap);

    }

    @PostMapping("/richtext_upload")
//    @RequestMapping(value = "/richtext_upload", produces = {"text/html;charset=UTF-8"},method=RequestMethod.POST)
    @ResponseBody
    public WangEditorVO richtext_upload(@RequestPart("files") MultipartFile[] files ) throws FileNotFoundException {
        //填充业务
        System.out.println("文件名"+files);
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        //文件上传的路径放入编译target目录下面 2、服务器的路径
        File upload = new File(path.getAbsolutePath(), "/static/upload");
        System.out.println("upload"+upload);
        System.out.println(files.length);

        WangEditorVO wangEditorVO = new WangEditorVO();
        if (files != null && files.length > 0){
//            Map<String,String> map = new HashMap<>();
            String imgUrls[] = new String[files.length];
               for (int i = 0; i < files.length;i++) {

                   System.out.println(files[i].getOriginalFilename());

                   String fileName = files[i].getOriginalFilename();
                   String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
                   String uploadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;
                   logger.info("开始上传文件,编号" + i);
                   if (!upload.exists()) {
                       upload.setWritable(true);
                       upload.mkdirs();
                   }
                   File targetFile = new File(upload, uploadFileName);

                   try {
                       files[i].transferTo(targetFile);//使用transferTo（dest）方法将上传文件写到服务器上指定的文件。

                       FTPUtil.uploadFile(Lists.newArrayList(targetFile));
                       //已上传到FTP服务器上

                       targetFile.delete();
                   } catch (IOException e) {
                       logger.error("上传文件异常", e);
                   }

                   String targetFileName = targetFile.getName();

                   //获取前缀ftp服务器的图片前缀
                   String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
                   if (targetFileName == null) {
                       return null;
                   }

                   //存储到字符串数组
                   imgUrls[i] = url;
               }
                wangEditorVO.setErrno(0);
                wangEditorVO.setData(imgUrls);
                return wangEditorVO;
        }
        return null;
    }


    @PostMapping("/uploadDel")
    @ResponseBody
    public Result uploadDel(String fileName) {
        try {
           boolean delResult =  FTPUtil.delUploadFile(fileName);
            if (delResult == true)
                return ResultGenerator.getSuccessResult("删除文件成功！");
        } catch (IOException e) {
            logger.error("上传文件异常",e);
        }
        return ResultGenerator.getFailResult("删除文件失败！");
    }


    @GetMapping({"/index","index.html","/"})
    public String indexPage(Model model){
        List<IndexNewProductVO> newProduct = iProductService.newProduct();

        model.addAttribute("newProduct",newProduct);
        return "mall/index";
    }

}
